/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.motoo.core;

import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;

import com.google.code.motoo.utils.IoSessionUtils;

/**
 * 
 * @author linfengqi
 * @version 1.0  May 13, 2009
 */
public class TimeoutControl implements Runnable{
	private final static Object lock = new Object();
	private volatile boolean enableTimeout;
	private long maxIdleTime;
	private final static int DEFAULT_IDLE_TIME = 60 * 1000;

	public TimeoutControl() {
		this(false, Long.MAX_VALUE);
	}
	
	public TimeoutControl(boolean enableTimeout, long maxIdleTime) {
		this.maxIdleTime = maxIdleTime;
		this.enableTimeout = enableTimeout;
	}
	
	public void init() {
		if (enableTimeout) {
			if (maxIdleTime <= 0) maxIdleTime = DEFAULT_IDLE_TIME;
			Thread thread = new Thread(this);
			thread.setDaemon(true);
			thread.start();
		}
	}
	
	public void destory() {
		enableTimeout = false;
	}

	public void run() {
		while(enableTimeout) {
			ConcurrentMap<SocketChannel, IoSession> containor = IoSessionUtils.getContainor();
			Set<SocketChannel> keySet = containor.keySet();
			int size = containor.size();
			if (size > 0) {
				long currentTime = System.currentTimeMillis();
				synchronized(keySet) {
					Iterator<SocketChannel> iter = keySet.iterator();
					while(iter.hasNext()) {
						SocketChannel key = iter.next();
						IoSession session = containor.get(key);
						boolean isTimeout = session.timeout(currentTime, maxIdleTime);
						if (isTimeout) {
							iter.remove();
							session.close();
						}
					}
				}
			}
			
			processExpires();
			
			try {
                Thread.sleep(maxIdleTime);
            } catch (InterruptedException e) {
            }
		}
	}
	
	private void processExpires() {
        long timeNow = System.currentTimeMillis();

        /*for (ExpiringObject o : delegate.values()) {

            if (timeToLiveMillis <= 0) {
                continue;
            }

            long timeIdle = timeNow - o.getLastAccessTime();

            if (timeIdle >= timeToLiveMillis) {
                delegate.remove(o.getKey());

                for (ExpirationListener<V> listener : expirationListeners) {
                    listener.expired(o.getValue());
                }
            }
        }*/
    }
	

	public boolean isEnableTimeout() {
		return enableTimeout;
	}

	public void setEnableTimeout(boolean enableTimeout) {
		this.enableTimeout = enableTimeout;
	}

	public long getMaxIdleTime() {
		return maxIdleTime;
	}

	public void setMaxIdleTime(long maxIdleTime) {
		this.maxIdleTime = maxIdleTime;
	}
	
}
